﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AutoServey
{
    public class SocketClient
    {
        static string SocketServerIP = "192.168.1.100";
        static int SocketServerPort = 8888;
        private bool beConnected = false;
        string filePath = "";
        Socket socket = null;
        public void SocketConnect()
        {
            IPAddress ip = IPAddress.Parse(SocketServerIP);
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Connect(new IPEndPoint(ip, SocketServerPort));
            beConnected = true;
            //ClientRun();
            Thread receiveThread = new Thread(new ThreadStart(ClientRun));
            receiveThread.Start();
        }

        public void ClientRun()
        {
            SendInfo("AnyCatchSVTask");
            while (this.beConnected)
            {
                string InfoType = GetInfoType();
                if (InfoType == "NewCatchSVTask")
                {
                    filePath = string.Format("{0}/NewCatchSVTask/{1}.zip", FrmMain.GetInstance().AppPath, Guid.NewGuid().ToString());
                    Console.WriteLine("CatchSVClient:<<<<<<<<<<<<<<GET NewCatchSVTaskInfo");
                    
                    if (ReceiveFile(filePath))
                    {
                        frmMainMethods mMethods = new frmMainMethods();
                        string resultPath = mMethods.StartCatchSv(filePath);
                        mMethods.deleteAllCache();
                        Thread.Sleep(1000);
                        SendInfo("CatchedSVTask");
                        SendFile(resultPath);
                        //TODO--发送成功删除所有缓存

                    }
                    SendInfo("AnyCatchSVTask");
                }
                else if (InfoType == "NoCatchSVTask")
                {
                    Console.WriteLine("CatchSVClient:<<<<<<<<<<<<<<GET NoCatchSVTaskInfo");
                    Thread.Sleep(60000);
                    SendInfo("AnyCatchSVTask");
                }
            }
        }

        public string GetInfoType()
        {
            string infoType = "";
            byte[] getBytes = new byte[1024];
            int index = this.socket.Receive(getBytes);
            infoType = Encoding.Default.GetString(getBytes, 0, index);
            return infoType;
        }

        public void SendInfo(string info)
        {
            byte[] sendBytes = new byte[1024];
            sendBytes = Encoding.ASCII.GetBytes(info);
            socket.Send(sendBytes, sendBytes.Length, SocketFlags.None);
        }

        public bool SendFile(string filePath)
        {
            Console.WriteLine("CatchSVClient:===============Start Send File");
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            long fileLeftLength = fs.Length;
            byte[] sendBytes = new byte[1024];
            sendBytes = Encoding.ASCII.GetBytes(fileLeftLength.ToString());
            int lenIndex = 0;
            try
            {
                lenIndex = socket.Send(sendBytes);
            }
            catch (System.Exception ex)
            {
                fs.Close();
                return false;
            }
            if (lenIndex < 1024)
            {
                byte[] nullBytes = new byte[1024 - lenIndex];
                try
                {
                    socket.Send(nullBytes);
                }
                catch (System.Exception ex)
                {
                    fs.Close();
                    return false;
                }
            }
            while (fileLeftLength > 0)
            {
                int index = fs.Read(sendBytes, 0, sendBytes.Length);
                try
                {
                    socket.Send(sendBytes, 0, index, SocketFlags.None);
                }
                catch (System.Exception ex)
                {
                    fs.Close();
                    return false;
                }
                fileLeftLength -= index;
            }
            fs.Close();
            Console.WriteLine("CatchSVClient:===============Finish Send File");
            return true;
        }

        public bool ReceiveFile(string filePath)
        {
            int index = 0;
            byte[] receiveBytes = new byte[1024];
            Console.WriteLine("CatchSVClient:===============Start Received File");

            //先接收文件长度信息
            try
            {
                index = socket.Receive(receiveBytes);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("CatchSVClient:*******************Failed Received File");
                return false;
            }
            string lengthStr = Encoding.Default.GetString(receiveBytes);
            int fileLeftLength = Convert.ToInt32(lengthStr);
            Console.WriteLine("CatchSVClient:############This file's length is " + fileLeftLength);

            FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            BinaryWriter bw = new BinaryWriter(fs);
            //循环接收文件
            while (fileLeftLength > 0)
            {
                try
                {
                    index = socket.Receive(receiveBytes);
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine("CatchSVClient:*******************Failed Received File");
                    bw.Close();
                    fs.Close();
                    return false;
                }
                bw.Write(receiveBytes, 0, index);
                fileLeftLength -= index;
            }
            Thread.Sleep(1000);
            Console.WriteLine("CatchSVClient:===============Finish Received File");
            bw.Close();
            fs.Close();
            return true;
        }

    }
}
